#include "serial.h"

#define _WIN32_WINNT 0x0601
#include <boost/asio.hpp>

class SerialDetails {
public:
    boost::asio::io_service io;
    boost::asio::serial_port serial;

    SerialDetails(std::string port, unsigned int baud_rate): io(), serial(io,port) {
        serial.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
    }

};

Serial::Serial(std::string port, unsigned int baud_rate, QObject *parent):
    QThread(parent),
    details(new SerialDetails(port, baud_rate)),
    m_running(true), m_counter(0)
{}

void Serial::writeString(std::string s)
{
    boost::asio::write(details->serial,boost::asio::buffer(s.c_str(),s.size()));
}


void Serial::run() {
    while(m_running) {
        ++m_counter;
    QString tmp( readLine().c_str() );	// String von serieller Schnittstelle lesen
    emit(message(tmp));			// String als Signal senden
        msleep(20);
    }
}

std::string Serial::readLine()
{
    //Reading data char by char, code is optimized for simplicity, not speed
    using namespace boost;
    char c;
    std::string result;
    for(;;)
    {
        asio::read(details->serial,asio::buffer(&c,1));
        switch(c)
        {
            case '\r':
                break;
            case '\n':
                return result;
            default:
                result+=c;
        }
    }
}

